// pages/preferences/preferences.js
const themeManager = require("../../utils/theme.js");

Page(themeManager.enhancePage({
  data: {
    theme: 'dark', // 默认深色主题
    notificationEnabled: true,
    autoRefresh: true,
    currentTheme: 'dark' // 添加主题状态
  },

  onLoad: function (options) {
    this.loadPreferences();
  },

  // 加载偏好设置
  loadPreferences: function() {
    const theme = wx.getStorageSync('theme') || 'dark';
    const notificationEnabled = wx.getStorageSync('notificationEnabled');
    const autoRefresh = wx.getStorageSync('autoRefresh');
    
    this.setData({
      theme: theme,
      notificationEnabled: notificationEnabled !== false, // 默认开启
      autoRefresh: autoRefresh !== false // 默认开启
    });
    
    // 应用主题（通过全局主题管理器）
    const app = getApp();
    app.applyGlobalTheme(theme);
  },

  // 切换主题
  switchTheme: function(e) {
    const theme = e.currentTarget.dataset.theme;
    this.setData({ theme: theme });
    
    // 使用全局主题管理器切换主题
    const app = getApp();
    app.switchTheme(theme);
    
    // 显示提示
    wx.showToast({
      title: `已切换到${theme === 'light' ? '浅色' : '深色'}主题`,
      icon: 'success',
      duration: 1500
    });
    
    // 发送主题变更事件
    wx.setStorageSync('themeChanged', Date.now());
  },



  // 通知设置变更
  onNotificationChange: function(e) {
    const enabled = e.detail.value;
    this.setData({ notificationEnabled: enabled });
    wx.setStorageSync('notificationEnabled', enabled);
    
    wx.showToast({
      title: enabled ? '已开启通知' : '已关闭通知',
      icon: 'success',
      duration: 1500
    });
  },

  // 自动刷新设置变更
  onAutoRefreshChange: function(e) {
    const enabled = e.detail.value;
    this.setData({ autoRefresh: enabled });
    wx.setStorageSync('autoRefresh', enabled);
    
    wx.showToast({
      title: enabled ? '已开启自动刷新' : '已关闭自动刷新',
      icon: 'success',
      duration: 1500
    });
  },

  onShow: function() {
    // 页面显示时重新加载设置
    this.loadPreferences();
  }
}));